//
//  TGTrendListViewController.m
//  WanCaiC8
//
//  Created by QiuXun on 2019/1/17.
//  Copyright © 2019 tangang. All rights reserved.
//

#import "TGTrendListViewController.h"
#import "LabCell.h"
#import "LotteryLayout.h"
#import "InformationVM.h"
#import "TGTrendListModel.h"
#import "TGTrendListDetal_LogoModel.h"
#import "TGTrendListDetal_UrlModel.h"

#import "TGTrendListCollectionReusableView.h"

#import "TGMaskCollectionView.h"

#import "TGAdvertCollectionViewCell.h"


@interface TGTrendListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic ,strong) UICollectionView  *collectionView;

//接口返回的元数据Data
@property(nonatomic,strong)NSMutableArray *dataArr;



//大分类 六合彩 快三 时时彩
@property(nonatomic,strong)NSMutableArray<TGTrendListModel *> *trendListArr;

//保存一个字典数组
@property(nonatomic,strong)NSMutableArray<NSMutableDictionary *> *selectArr;

@property(nonatomic,strong)NSMutableArray *arr1;
@property(nonatomic,strong)NSMutableArray *arr2;
//记录isdisplay为1 的数组
@property(nonatomic,strong)NSMutableArray *colArr1;
@property(nonatomic,strong)NSMutableArray *colArr2;


//记录 第0组不包含广告cell的cell个数
@property(nonatomic,assign)NSInteger cellCount0;
//记录 第2组不包含广告cell的cell个数
@property(nonatomic,assign)NSInteger cellCount2;


@end

@implementation TGTrendListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"彩票走势图";
    
    
    [self setRightNavItem];
    [SVProgressHUD show];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self getTrendList];
        
        
        
        
    });
    
}


#pragma mark -- 获取广告
- (void)getAdvertising{
        self.arr1=[[NSMutableArray alloc]init];
     self.arr2=[[NSMutableArray alloc]init];
     self.colArr1=[[NSMutableArray alloc]init];
     self.colArr2=[[NSMutableArray alloc]init];
   
    [[InformationVM manage] getAdvertWithLocation:@"0" andType:14 Success:^(id returnValue) {
        
        for (AdvertisingModel *model in returnValue) {
            
            NSLog(@"%ld--%ld",model.Layer,model.IsDisplay);
            
            if (model.Display) {
                if (model.Layer==1) {
                    [self.arr1 addObject:model];
                    if (model.IsDisplay) {
                        [self.colArr1 addObject:model];
                    }
                }else if (model.Layer==2){
                    [self.arr2 addObject:model];
                    if (model.IsDisplay) {
                        [self.colArr2 addObject:model];
                    }
                }
            }
        }
        
        [self.collectionView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
        [self.collectionView reloadData];
    }];
}

-(void)setRightNavItem{
    
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(onclickNav)];
    self.navigationItem.rightBarButtonItem=rightItem;
    
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
     [SVProgressHUD dismiss];
}
#pragma mark -- 获取图库走势图列表
-(void)getTrendList{
    
    
    [[InformationVM manage] getTrendListSuccess:^(id returnValue) {
        
        [SVProgressHUD dismiss];
        
     
        self.trendListArr = [NSMutableArray arrayWithArray:[TGTrendListModel mj_objectArrayWithKeyValuesArray:[returnValue objectForKey:@"Data"]]];
        
        self.selectArr = [NSMutableArray array];
        
        for ( int i=0; i<self.trendListArr.count ; i++) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            
            //选中的是第几组 大分类
            [dic setValue:[NSString stringWithFormat:@"%d",i] forKey:@"section"];
            //切换彩种 选中的是第几个 小分类
            [dic setValue:@"0" forKey:@"row"];
            
            [self.selectArr addObject:dic];

        }
       
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self getAdvertising];
        });

        
        
    } Fail:^(NSString *errorMessage, NSError *error) {
        
       
        
    }];
    
    
    
}


#pragma mark - collectionView代理函数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return self.trendListArr.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
 
    TGTrendListModel  *trendListModel = self.trendListArr[section];

    NSInteger selectRow = [[self.selectArr[section] objectForKey:@"row"] integerValue];
    
    //根据section  解析 大彩种下的小彩种
    NSArray *arr =[TGTrendListDetal_LogoModel mj_objectArrayWithKeyValuesArray: trendListModel.trendList];
    
    NSLog(@"%ld",arr.count);
    
    //每个小彩种下的栏目列表
    NSArray *subArr = [TGTrendListDetal_UrlModel mj_objectArrayWithKeyValuesArray:[arr[selectRow] trend_LogoList]];
    
    
    if (section ==0) {
        self.cellCount0 = subArr.count;
        return subArr.count + (self.arr1?1:0);
    }
    if (section ==2) {
        
        self.cellCount2 = subArr.count;
        return subArr.count + (self.arr2?1:0);
    }
    
   
    return subArr.count;
    
}
//

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
   
    
    //快三模型TGTrendListModel name arr
    TGTrendListModel  *trendListModel = self.trendListArr[indexPath.section];
    
    //    self.selectArr
    //这里需要取dic
    NSInteger selectRow = [[self.selectArr[indexPath.section] objectForKey:@"row"] integerValue];
    
    //根据section  解析 大彩种下的小彩种
    NSArray *arr =[TGTrendListDetal_LogoModel mj_objectArrayWithKeyValuesArray: trendListModel.trendList];
 
    TGTrendListDetal_LogoModel *model = arr[selectRow];
  
    
        //每个小彩种下的栏目列表
    NSArray *subArr = [TGTrendListDetal_UrlModel mj_objectArrayWithKeyValuesArray:[model trend_LogoList]];
    
    
    if (indexPath.row<subArr.count) {
        LabCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"LabCell" forIndexPath:indexPath];

        [cell setLineTitle: [subArr[indexPath.row] Name]];
        return cell;
    }else{
        
        TGAdvertCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TGAdvertCollectionViewCell" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
            cell.dataArr = self.arr1;
        }
        if (indexPath.section == 2) {
            cell.dataArr = self.arr2;
        }
        
        return cell;
        
    }
        
  
  
   
    
}

//- (UICollectionViewCell *)cellWithModel:(AdvertisingModel *)model andIndexPath:(NSIndexPath *)indexPach{
//    if (model.ThumbStyle==0) {
//        AdvertisingNoImageCell *cell=[self.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingNoImageCell" forIndexPath:indexPach];
//        [cell setModel:model];
//        [cell showLine:indexPach.row==0];
//        return cell;
//    }else if (model.ThumbStyle==1){
//        AdvertisingSmallImageCell *cell=[self.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingSmallImageCell" forIndexPath:indexPach];
//        [cell setModel:model];
//        return cell;
//
//    }else if (model.ThumbStyle==2){
//        AdvertisingBigImageCell *cell=[self.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingBigImageCell" forIndexPath:indexPach];
//        [cell setModel:model];
//        return cell;
//    }else if (model.ThumbStyle==3){
//        AdvertisingMoreImageCell *cell=[self.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingMoreImageCell" forIndexPath:indexPach];
//        [cell setModel:model];
//        return cell;
//    }else{
//        ImageCell *cell=[self.collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPach];
//        if (model.ThumbList.count>0) {
//            [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.ThumbList[0]] placeholderImage:[UIImage imageNamed:@"big_loding"]];
//        }else{
//            cell.imageV.image=[UIImage imageNamed:@"big_loding"];
//        }
//        return cell;
//    }
//}

//ui
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section ==0 ) {
        
        if (indexPath.row<self.cellCount0) {
            return CGSizeMake(SCREEN_WIDTH/4.0, 40);
        }else{
          
            
            return CGSizeMake(SCREEN_WIDTH,(self.arr1.count ?10:0)+self.arr2.count*40-ceil(self.colArr1.count/2.0)*40);
            
        }
        
    }else if (indexPath.section ==2){
        
        if (indexPath.row<self.cellCount2) {
            return CGSizeMake(SCREEN_WIDTH/4.0, 40);
        }else{
            
                return CGSizeMake(SCREEN_WIDTH,(self.arr2.count ?10:0)+self.arr2.count*40-ceil(self.colArr2.count/2.0)*40);
           
        }
    }
    
    return CGSizeMake(SCREEN_WIDTH/4.0, 40);
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(SCREEN_WIDTH, 40);
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableView = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        
        TGTrendListCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TGTrendListCollectionReusableView" forIndexPath:indexPath];
        
        
        //快三模型TGTrendListModel name arr
        TGTrendListModel  *trendListModel = self.trendListArr[indexPath.section];
        //    self.selectArr
        //这里需要取dic
        NSInteger selectRow = [[self.selectArr[indexPath.section] objectForKey:@"row"] integerValue];
        
        //根据section  解析 大彩种下的小彩种
        NSArray *arr =[TGTrendListDetal_LogoModel mj_objectArrayWithKeyValuesArray: trendListModel.trendList];
        
        
        if (arr.count == 1) {
            headerView.isHiddenChane = YES;
        }else{
            headerView.isHiddenChane = NO;
        }
 
        TGTrendListDetal_LogoModel *model = arr[selectRow];
        
        if (indexPath.section ==0) {
            headerView.isHiddenLineView = YES;
        }else{
             headerView.isHiddenLineView = NO;
        }
        
        headerView.iconUrl = model.Logo;
        headerView.title = model.Name;
        
        __weak TGTrendListCollectionReusableView *weakHeadView = headerView;
        
        headerView.chaneBlock = ^{
            
            __strong TGTrendListCollectionReusableView * strongHeadView = weakHeadView;
            CGRect tempRect = [strongHeadView convertRect:strongHeadView.bounds toView:[UIApplication sharedApplication].keyWindow];
           
            
            
            TGTrendListModel  *trendListModel = self.trendListArr[indexPath.section];
            //    self.selectArr
            //这里需要取dic
            NSInteger deleteRow = [[self.selectArr[indexPath.section] objectForKey:@"row"] integerValue];
//
            //根据section  解析 大彩种下的小彩种
            NSMutableArray *arr =[NSMutableArray arrayWithArray:[TGTrendListDetal_LogoModel mj_objectArrayWithKeyValuesArray: trendListModel.trendList]];

            CGRect rect;
            if (arr.count<=4) {

                rect = CGRectMake(tempRect.origin.x,tempRect.origin.y +tempRect.size.height , SCREEN_WIDTH, 40);
                
            }else{
                
                rect=CGRectMake(tempRect.origin.x,tempRect.origin.y +tempRect.size.height , SCREEN_WIDTH, 40*2);
            }
           

            TGMaskCollectionView *maskView= [[TGMaskCollectionView alloc] initWithFrame:rect];
            
            
            ///剔除数据
            [arr removeObjectAtIndex:deleteRow];
            maskView.dataArr = arr.copy;
            [maskView show];
            
            
            ///获取点击的indexPath.section
            NSLog(@"%ld",indexPath.section);

            maskView.chaneBlock = ^(NSString * _Nonnull Name) {
                
                NSLog(@"%@",Name);
                
                
                //重新解析数据
                NSArray *tempArr =[TGTrendListDetal_LogoModel mj_objectArrayWithKeyValuesArray: trendListModel.trendList];
                //遍历找出所在位置
                NSInteger tempRow = 0;
                for (int i=0; i<tempArr.count; i++) {
                    TGTrendListDetal_LogoModel *model = tempArr[i];
                    if ([Name isEqualToString:model.Name]) {
                        tempRow = i;
                    }
                }
        
                
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setValue:[NSString stringWithFormat:@"%ld",indexPath.section] forKey:@"section"];
                [dic setValue:[NSString stringWithFormat:@"%ld",tempRow] forKey:@"row"];
                
                [self.selectArr replaceObjectAtIndex:indexPath.section withObject:dic];
            
                NSLog(@"%@",self.selectArr);
                
                [self.collectionView reloadData];
                        
                //reloda
                //更新数据
                //记录 selectedArr
                NSLog(@"changeBLock %@",arr);
                
               
            };
            
        
            
            
            
        };

        
        reusableView = headerView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    //快三模型TGTrendListModel name arr
    TGTrendListModel  *trendListModel = self.trendListArr[indexPath.section];
    //    self.selectArr
    //这里需要取dic
    NSInteger selectRow = [[self.selectArr[indexPath.section] objectForKey:@"row"] integerValue];
    
    //根据section  解析 大彩种下的小彩种
    NSArray *arr =[TGTrendListDetal_LogoModel mj_objectArrayWithKeyValuesArray: trendListModel.trendList];
    
    TGTrendListDetal_LogoModel *model = arr[selectRow];
    
    //每个小彩种下的栏目列表
    NSArray *subArr = [TGTrendListDetal_UrlModel mj_objectArrayWithKeyValuesArray:[model trend_LogoList]];
    
    TGTrendListDetal_UrlModel *urlModel =subArr[indexPath.row];
    
    PublicWebVC *vc=[[PublicWebVC alloc]init];
    vc.saveViewController =self;
    vc.isHaddenNav = YES;
    vc.isAll = YES;
    vc.url=urlModel.Url;
    [self.navigationController pushViewController:vc animated:YES];
  

//
//    if (indexPath.section==0) {
//        AdvertisingModel *model=arr2[indexPath.row];
//
//        if ([model.Title containsString:@"】"]) {
//
//            UIPasteboard *copy = [UIPasteboard generalPasteboard];
//            NSRange startRange = [model.Title rangeOfString:@"【"];
//            NSRange endRange = [model.Title rangeOfString:@"】"];
//            NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
//            NSString *result = [model.Title substringWithRange:range];
//
//            [copy setString:result];
//
//            [SVProgressHUD showSuccessWithStatus:@"复制成功"];
//
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [SVProgressHUD dismiss];
//                [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
//            });
//
//        }else{
//            if (model.TransferUrl.length<1) {
//                return;
//            }
//
//            [[UIApplication sharedApplication]openURL:[NSURL URLWithString: model.TransferUrl]];
//
//        }
//    }
//    else if (indexPath.section == 1){
//
//        if (indexPath.row<self.palyInfoArr.count) {
//
//            //进入高手计划
//            MasterListVC *vc=[[MasterListVC alloc]init];
//            vc.lType=self.typeModel.Id;
//            vc.strTitle = self.typeModel.LTypeName;
//
//
//            if (indexPath.row <=3) {
//
//
//                vc.dic = @{@"selectRule":@"0",@"selectSubRule":[NSString stringWithFormat:@"%zd",indexPath.row],@"title":@"特码"};
//
//            }else if (indexPath.row == 4){
//
//                vc.dic = @{@"selectRule":@"1",@"selectSubRule":@"0",@"title":@"五不中"};
//
//            }else{
//
//                vc.dic = @{@"selectRule":@"2",@"selectSubRule":[NSString stringWithFormat:@"%zd",indexPath.row-5],@"title":@"生肖"};
//            }
//
//
//            [self.navigationController pushViewController:vc animated:YES];
//
//        } else {
//
//            AdvertisingModel *model=arr4[indexPath.row-self.palyInfoArr.count];
//            if (model.TransferUrl.length<1) {
//                return;
//            }
//            if ([model.Title containsString:@"】"]) {
//
//                UIPasteboard *copy = [UIPasteboard generalPasteboard];
//                NSRange startRange = [model.Title rangeOfString:@"【"];
//                NSRange endRange = [model.Title rangeOfString:@"】"];
//                NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
//                NSString *result = [model.Title substringWithRange:range];
//
//                [copy setString:result];
//
//                [SVProgressHUD showSuccessWithStatus:@"复制成功"];
//
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [SVProgressHUD dismiss];
//                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
//                });
//
//            }else{
//
//                [[UIApplication sharedApplication]openURL:[NSURL URLWithString: model.TransferUrl]];
//
//            }
//
//
//        }
//
//
//
//
//
//    }
//
//    else if (indexPath.section==2){
//        if (indexPath.row<self.newsPicArr.count) {
//            NewsTypeModel *model=self.newsPicArr[indexPath.row];
//            for (int i=0; i<self.dataArr.count; i++) {
//                NewsTypeModel *tModel=self.dataArr[i];
//                if ([model.Id isEqualToString:tModel.Id]) {
//                    model.index=i;
//                    break;
//                }
//            }
//            if (self.selectType) {
//                self.selectType(model);
//            }
//        }else{
//            AdvertisingModel *model=arr6[indexPath.row-self.newsPicArr.count];
//            if (model.TransferUrl.length<1) {
//                return;
//            }
//            if ([model.Title containsString:@"】"]) {
//
//                UIPasteboard *copy = [UIPasteboard generalPasteboard];
//                NSRange startRange = [model.Title rangeOfString:@"【"];
//                NSRange endRange = [model.Title rangeOfString:@"】"];
//                NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
//                NSString *result = [model.Title substringWithRange:range];
//
//                [copy setString:result];
//
//                [SVProgressHUD showSuccessWithStatus:@"复制成功"];
//
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [SVProgressHUD dismiss];
//                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
//                });
//
//            }else{
//
//                [[UIApplication sharedApplication]openURL:[NSURL URLWithString: model.TransferUrl]];
//
//            }

//        }
//
//    }else if (indexPath.section==3) {
//        if (indexPath.row<self.newsTypeArr.count) {
//            NewsTypeModel *model=self.newsTypeArr[indexPath.row];
//            for (int i=0; i<self.dataArr.count; i++) {
//                NewsTypeModel *tModel=self.dataArr[i];
//                if ([model.Id isEqualToString:tModel.Id]) {
//                    model.index=i;
//                    break;
//                }
//            }
//            if (self.selectType) {
//                self.selectType(model);
//            }
//        }else{
//            AdvertisingModel *model=arr8[indexPath.row-self.newsTypeArr.count];
//            if (model.TransferUrl.length<1) {
//                return;
//            }
//            if ([model.Title containsString:@"】"]) {
//
//                UIPasteboard *copy = [UIPasteboard generalPasteboard];
//                NSRange startRange = [model.Title rangeOfString:@"【"];
//                NSRange endRange = [model.Title rangeOfString:@"】"];
//                NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
//                NSString *result = [model.Title substringWithRange:range];
//
//                [copy setString:result];
//
//                [SVProgressHUD showSuccessWithStatus:@"复制成功"];
//
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [SVProgressHUD dismiss];
//                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
//                });
//
//            }else{
//
//                [[UIApplication sharedApplication]openURL:[NSURL URLWithString: model.TransferUrl]];
//
//            }
//        }
//    }
}


#pragma mark -- 懒加载
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        LotteryLayout *layout = [[LotteryLayout alloc] init];
        layout.cellType=AlignWithLeft;
        [layout setItemSize:CGSizeMake(floor(SCREEN_WIDTH/3.0) , 40)];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator=NO;
        [_collectionView registerClass:[LabCell class] forCellWithReuseIdentifier:@"LabCell"];

        [_collectionView registerClass:[TGTrendListCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TGTrendListCollectionReusableView"];
        
        [_collectionView registerClass:[TGAdvertCollectionViewCell class] forCellWithReuseIdentifier:@"TGAdvertCollectionViewCell"];
        
        [self.view addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _collectionView;
}


@end
